data = [
    {"id": "1", "name": "数据1", "parent_id": ''},
    {"id": "2", "name": "数据2", "parent_id": "1"},
    {"id": "3", "name": "数据3", "parent_id": "1"},
    {"id": "4", "name": "数据4", "parent_id": "5"},
    {"id": "5", "name": "数据5", "parent_id": ''},
    {"id": "6", "name": "数据6", "parent_id": "6"},
    {"id": "7", "name": "数据7", "parent_id": "6"},
]

def build_tree(data: list[dict],id_field= "id", parent_id_field= "parent_id"):
    data_map = {}
    tree = []
    def is_blank(field):
        type_field=type(field)
        if field is None:
            return True
        if type_field==str:
            if field=="":
                return True
            return field.isspace()
        return False
    # 构建一个字典，以 id 为键，整个字典为值
    for item in data:
        data_map[item[id_field]] = item
        item["children"] = []  # 初始化 children 字段
    # 构建树形结构
    for item in data:
        parent_id = item[parent_id_field]
        if is_blank(parent_id) :
            # 如果 parent_id 为 None，说明是根节点
            tree.append(item)
        else:
            # 如果 parent_id 不为 None，找到其父节点，并将当前节点添加到父节点的 children 中
            parent = data_map.get(parent_id)
            if parent:
                parent["children"].append(item)
    return tree

print(build_tree(data))